/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;
import opiam.admin.applis.demo.forms.PersonForm;
import opiam.admin.applis.demo.utils.GenerateTree;
import opiam.admin.applis.demo.utils.PasswordUtils;

import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.service.services.views.TreeNode;
import opiam.admin.faare.service.services.views.ViewGenerator;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;


/**
 * This class allows to create a person entry.
 *
 * This Action class inherits from SecureAction class.
 * The SecureAction class checks that the user is connected before calling
 * the action methods.
 */
public class CreatePersonAction extends SecureAction
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger = Logger.getLogger(CreatePersonAction.class);

    /**
     * This method is called to execute the action once the checks have been
     * performed by the SecureAction class.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();

            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            // Gets the user context.
            UserContext userContext = sessionContext.getUserContext();

            // Gets the user
            PersonForm pf = (PersonForm)actionForm;
            Person person = pf.getUser();

            // checks the userId
            if (person.getId() == null)
            {
                msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                              new ActionMessage("User Id is mandatory !")
                             );
                saveErrors(request, msgErrors);

                return mapping.findForward("error");
            }
            
            // Manages the password attribute
            String newP = pf.getNewPassword();
            String confP = pf.getConfirmPassword();

            _logger.debug("New password : " + newP);
            
            // checks the password
            if ((newP != null) && (newP.trim().length() > 0))
            {
                if (!newP.equals(confP))
                {
                    msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                                  new ActionMessage("error.password.nomatch")
                                 );
                    saveErrors(request, msgErrors);

                    return mapping.findForward("error");
                }

                person.setPassword(newP);

                // deletes the values in the form
                pf.setNewPassword("");
                pf.setConfirmPassword("");

                // checks the syntax
                if (!PasswordUtils.checkPassword(newP))
                {
                    msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                                  new ActionMessage("error.password.constraints")
                                 );
                    saveErrors(request, msgErrors);

                    return mapping.findForward("error");
                }
            }
            
            // Manages the displayname and the commonName
            StringBuffer sb = new StringBuffer();
            sb.append(person.getGivenName());
            sb.append(" ");
            sb.append(person.getName());
            person.setCommonName(sb.toString());
            
            sb = new StringBuffer();
            sb.append(person.getName());            
            sb.append(" ");            
            sb.append(person.getGivenName());
            person.setDisplayName(sb.toString());
            
            // Manages the description
            if (pf.getDescrp() != null)
            {
                person.setDescription(pf.getDescription());
            }
            
            // Manages the managers
            if (pf.getManagerPerson() != null)
            {
            	person.setManager(pf.getManagerInPerson());
            }
            else
            {
            	person.setManager(new ArrayList());
            }
            
            // Manages the photo
            FormFile file = pf.getPhotoFile();

            if ((file != null) && (file.getFileSize() > 0))
            {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream stream = file.getInputStream();

                byte[] buffer = new byte[8192];
                int bytesRead = 0;

                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1)
                {
                    baos.write(buffer, 0, bytesRead);
                }

                _logger.debug("baos.size() = " + baos.size());

                if (baos.size() > 0)
                {
                    Collection listBytes = new ArrayList();
                    listBytes.add(baos.toByteArray());
                    person.setPhoto(listBytes);
                }
            }
            
            
            // Manages the certificate
            FormFile certfile = pf.getCertificateFile();

            if ((certfile != null) && (certfile.getFileSize() > 0))
            {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream stream = certfile.getInputStream();

                byte[] buffer = new byte[8192];
                int bytesRead = 0;

                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1)
                {
                    baos.write(buffer, 0, bytesRead);
                }

                _logger.debug("baos.size() = " + baos.size());

                if (baos.size() > 0)
                {
                    Collection listBytes = new ArrayList();
                    listBytes.add(baos.toByteArray());
                    person.setCertificate(listBytes);
                }
            }

            // Sets the dn,  tree : ou=People, dc=mycompany,dc=com
            sb = new StringBuffer();
            sb.append("uid=");
            sb.append(person.getId());
            sb.append(",ou=People, dc=mycompany,dc=com");
            person.setDn(sb.toString());

            // Writes the operation on the output defined in the
            // logger_config.properties.
            _logger.info("Create person : " + person.getDn() + " by user: " +
                         sessionContext.getUserContext().getDn()
                        );
            
            StandardService.create(person, userContext);

            // Sets the modified entry in the session with the "currentEntry"
            // name.
            // This name is used in the jsp page by the Struts tags to
            // recover the attributes values of the person entry.
            session.setAttribute("currentEntry", person);

            // Sets the action fro the redirection page
            session.setAttribute("succeededOperation", "showCreatedPerson.do");
            
            session.removeAttribute("personForm");

            // Initializes the navigation
            TreeNode treeNode =
                ViewGenerator.generateTreeView(sessionContext.getUserContext());
            session.setAttribute("defaultTreeNode", treeNode);

            String tree =
                GenerateTree.getInstance().processTree(treeNode.getDefaultMutableTreeNode(),
                                                       null
                                                      );
            session.setAttribute("treeview", tree);
            
            
            // Returns the URI corresponding to the action success
            // as defined in the action configuration in the struts-config.xml.
            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            // Writes the error on the standard ouput console.
            se.printStackTrace();

            // Writes the error on the output defined in the
            // logger_config.properties.
            _logger.error(se.getMessage());

            // Gets the error message from the message-resources file
            // defined in the struts-config.xml
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );

            // Save the error message in the request to display it in the jsp
            // page.
            saveErrors(request, msgErrors);

            // Returns the Action-Forward corresponding to the error.
            return (mapping.findForward("error"));
        }
    }
}
